package com.youdoneed.user.application;

import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.enmus.ExcelType;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Excel导出工具类。
 */
public class ExcelUtils {

    /**
     * 导出Excel到HttpServletResponse。
     *
     * @param name Excel名称前缀。
     */
    public static <T> void exportToResponse(HttpServletResponse response,
                                            String name, Class<T> type, List<T> data) {
        // 开始导出
        ExportParams exportParams = new ExportParams();
        exportParams.setType(ExcelType.XSSF);
        exportParams.setSheetName("首页");
        Workbook workbook = ExcelExportUtil.exportExcel(
                exportParams, type, data);
        workbook.getSheetAt(0).setDefaultRowHeight((short) 450);
        response.setCharacterEncoding("UTF-8");
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM.getType());
        String fileName = name + new SimpleDateFormat("yyyyMMdd").format(new Date()) + ".xlsx";
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
